// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Form,Radio, Button,Table,Popconfirm, Modal, Row, Col, Input, Select, Cascader, Icon, Checkbox, Tabs, DatePicker, message } from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
import styles from './weekReportDetailStyle.less'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import { Grid } from 'widget/Grid/index'
import moment from 'moment';

const FormItem = Form.Item
const { RangePicker } = DatePicker
const { Option } = Select;
const { TextArea } = Input;
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const weekReportDetailView = function ({ dispatch, model, form }) {
  // 表单的子函数
  const { resetFields, getFieldDecorator, validateFields, setFieldsValue,validateFieldsAndScroll  } = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  let { cityList,areaList,products,query, actionType, btnLoading,loading } = modelObj

  const formItemLayoutPro = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
  };

  const columns = [
    {
      title: '产品类型', dataIndex: 'productType', key: 'productType', width: 100,
      render: function (value, item, index) {
        return item.productType
      }
    },
    {
      title: () => (
        <span>
          {'成交(套数)'}
          <span style={{color: 'red'}}>*</span>
        </span>
      ), dataIndex: 'numberOfTransactions', key: 'numberOfTransactions',width: 120,
      render: function (value, item, index) {
        return (<div key={item.id}>
          <FormItem style={{marginBottom: 0}}>
            {getFieldDecorator(`numberOfTransactions_${item.id}`, {
                rules: [{
                  required: true, message: '请输入成交(套数)'
                },{ pattern: /^[+-]?\d*\.?\d*$/, message: '请输入数字' }],
                initialValue: item.numberOfTransactions,
            })(
              <Input  disabled={actionType == 'check'}
                  onChange={(e) => { tableChange(e.target.value, 'numberOfTransactions',item.id) }}
                />
          )}
          </FormItem>
      </div>)
      }
    },
    {
      title: '毛坯/装修',dataIndex: 'houseStatus',key: 'houseStatus',width: 100,
      render: function (value, item, index) {
        return item.houseStatus
      }
    },
    {
      title:  () => (
        <span>
          {'均价(元/m²)'}
          <span style={{color: 'red'}}>*</span>
        </span>
      ), dataIndex: 'averagePrice', key: 'averagePrice',width: 120,
      render: function (value, item, index) {
        return (<div key={item.id}>
          <FormItem style={{marginBottom: 0}}>
            {getFieldDecorator(`averagePrice_${item.id}`, {
                rules: [{
                  required: true, message: '请输入均价'
                },{ pattern: /^[+-]?\d*\.?\d*$/, message: '请输入数字' }],
                initialValue: item.averagePrice,
            })(
              <Input disabled={actionType == 'check'} 
                onChange={(e) => { tableChange(e.target.value, 'averagePrice',item.id,item) }}
                />
            )}
          </FormItem>
      </div>)
      }
    }, 
    {
      title: '均价环比(%)', dataIndex: 'priceRatio', key: 'priceRatio',width: 120,
      render: function (value, item, index) {
        return <div>
        <Input style={{color: (item.priceRatio>=5||item.priceRatio<=-5)?'red':'#333333'}} value = {item.priceRatio}  disabled={true}
            onChange={(e) => { tableChange(e.target.value, 'priceRatio',item.id) }}
          />
      </div>
      }
    }, 
    {
      title: '单周推售情况', dataIndex: 'description', key: 'description',width: 300,
      render: function (value, item, index) {
        return <div>
        <TextArea style={{height: '32px'}} value = {item.description}  disabled={actionType == 'check'}
            onChange={(e) => { tableChange(e.target.value, 'description',item.id) }}
          />
      </div>
      }
    }, 
    {
      title: '浮动原因', dataIndex: 'reason', key: 'reason',width: 300,
      render: function (value, item, inde) {
      return (<div key={item.id}>
            <FormItem style={{marginBottom: 0}}>
              {getFieldDecorator(`reason_${item.id}`, {
                  rules: [{
                    required: (item.priceRatio>=5||item.priceRatio<=-5)?true:false, message: '请浮动原因'
                  }],
                  initialValue: item.reason,
              })(
                <TextArea style={{height: '32px'}} value = {item.reason}  disabled={actionType == 'check'}
                  onChange={(e) => { tableChange(e.target.value, 'reason',item.id) }}
                />
              )}
            </FormItem>
        </div>)
      }
    }, 
    {
      title:  () => (
        <span>
          {'合计总额(万元)'}
          <span style={{color: 'red'}}>*</span>
        </span>
      ), dataIndex: 'allPrice', key: 'allPrice',width: 120,
      render: (value, item, index) => {
        const obj = {
          children: value,
          props: {}
        };
        if (index === 0) {
          for(var ii of query.WeeklyCompet){
            if(item.competid == ii.competId){
              obj.props.rowSpan = ii.competitorInformation.length?ii.competitorInformation.length:1
            }
          }
          obj.children = (<div key={item.id}> 
                        <FormItem style={{marginBottom: 0}}>
                          {getFieldDecorator(`allPrice_${item.id}`, {
                              rules: [{
                                required: true, message: '请输入合计'
                              },{ pattern: /^[+-]?\d*\.?\d*$/, message: '请输入数字' }],
                              initialValue: item.allPrice,
                          })(
                          <Input disabled={actionType == 'check'}
                              onChange={(e) => { tableChange(e.target.value, 'allPrice',item.id) }}
                            />
                            )}
                        </FormItem>
                </div>)
        }else{
          obj.props.rowSpan = 0;
        }
        return obj;
      }
    }, 
  ]
 
  //日期改变时
  function dateChange(m,s){
    dispatch({
        type: `${namespace}/updateStore`,
        payload: {
            query: {
                ...query,
                beginTime: s[0],
                endTime: s[1],
            }
        }
    })
  }
  //输入框改变时
  function inputChange(value, name) {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        query: {
          ...query,
          [name]: value,
        }
      }
    })
    if(name == 'cityid'){
      dispatch({
        type: `${namespace}/findByProject`,
        payload: { cityid:value}
      })
    }
    if(name == 'projectid'){
      dispatch({
        type: `${namespace}/findCometingGoods`,
        payload: {projectId:value}
      })
    }
  }
  //区域改变时
  function inputAreaChange(value, name) {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        query: {
          ...query,
          [name]: value,
        }
      }
    })
    dispatch({
      type: `${namespace}/findByCity`,
      payload: {areaId:value}
    })
  }
  //表格改变时
  function tableChange (value, name,id,iit) {
    let obj = {[name]: value}
    for(var item of query.WeeklyCompet){
      for(var itemed of item.competitorInformation){
        if(itemed.id == id){
          itemed = Object.assign(itemed, obj)
        }
      }
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {query}
    })
    if(name == 'averagePrice'){
      dispatch({
        type: `${namespace}/getPriceRatio`,
        payload: {iit}
      })
    }
  }
  function submit(){
    validateFieldsAndScroll((err) => {
      if (err) {
        return false
      } else {
        dispatch({
          type: `${namespace}/submit`,
          payload: {}
        })
      }
    })
  }
  function deledeFun(id){
    query.WeeklyCompet = query.WeeklyCompet.filter(item => item.competid != id)
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {query}
    })
  }

  return (
    <div className='public_listMain'>
      <div className={"functionButton"}>
        <Button disabled={actionType == 'check'} type='primary' onClick={e => submit()} loading={btnLoading}>提交</Button>
      </div>

      <CollapsiblePanels title="竞品周报信息" hideUpDownBtn={true} >
        <Row>
          <Col span={8}>
          <FormItem
                {...formItemLayoutPro}
                label="生效时间"
                >
                {getFieldDecorator('effectiveTime', {
                    rules:[{required:true,message:'注：所选时间段内已存在竞品信息，请重新选择时间'}, 
                ],
                initialValue:query.beginTime?[moment(query.beginTime, 'YYYY-MM-DD'), moment(query.endTime, 'YYYY-MM-DD')]:[],
                })(
                    <RangePicker style={{width:'100%'}} disabled={actionType == 'check'} showTime={{
                        hideDisabledOptions: true
                      }}
                  format="YYYY-MM-DD" onChange={(date,dateString)=>{dateChange(date,dateString)}} 
                  onOk={(date)=>{}}
                  />
                )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='区域'  {...formItemLayoutPro}>
              {getFieldDecorator('areaid', {
                rules: [{
                  required: true, whitespace: true, message: '请选择区域'
                }],
                initialValue: query.areaid
              })(
                <Select disabled={actionType == 'check'} placeholder='请选择区域' onChange={(e) => { inputAreaChange(e, 'areaid') }}>
                    {areaList == undefined ?null:areaList.map((item)=>{
                      return <Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>
                    })}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='城市'  {...formItemLayoutPro}>
              {getFieldDecorator('cityid', {
                rules: [{
                  required: true, whitespace: true, message: '请选择城市'
                }],
                initialValue: query.city
              })(
                <Select disabled={actionType == 'check'} placeholder='请选择城市' onChange={(e) => { inputChange(e, 'cityid') }}>
                 {cityList == undefined ?null:cityList.map((item)=>{
                    return <Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>
                  })}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='项目名称'  {...formItemLayoutPro}>
              {getFieldDecorator('projectid', {
                rules: [{
                  required: true, whitespace: true, message: '请输入项目名称'
                }],
                initialValue: query.project
              })(
                <Select optionFilterProp="children" showSearch filterOption={true} disabled={actionType == 'check'} placeholder='请选择城市' onChange={(e) => { inputChange(e, 'projectid') }}>
                  {products == undefined ?null:products.map((item)=>{
                    return <Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>
                  })}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
      </CollapsiblePanels>
      <div style={{paddingLeft: '5%'}}><span style={{color: '#ff3b37'}}>*</span> 竞品信息</div>
      {query.WeeklyCompet.map((item,index)=>{
        return(<CollapsiblePanels key={index} title={item.competName + '('+item.competLevel+')'} hideUpDownBtn={true}  style={{position:'relative'}}>
                  <div onClick={e => deledeFun(item.competid)} style={{display:actionType == 'check'?'none':'block',position: 'absolute',top: '12px',right: '80px',zIndex: 9,color: 'red',cursor:'pointer'}}>删除</div>
                  <Table rowKey={(item, index) => {
                    return index
                }} columns={columns} dataSource={item.competitorInformation} pagination={false}/>
              </CollapsiblePanels>)
      })}
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(weekReportDetailView))